const fs = require("fs");
const path = require("path");
const chalk = require("chalk");
const asking = require("./asking");
const checkAndMkDir = require("./utils/checkAndMkDir");

function genfile(name) {
  const exist = fs.existsSync(name);
  if (!exist) fs.writeFileSync(name, "");
}

async function file(args, number) {
  const fpath = args[0];
  let prefix;
  let suffix;
  let inputNum;

  if (!fpath) {
    // 获取必要信息
    const answers = await asking("file", number);
    prefix = answers.prefix;
    suffix = answers.suffix ? `.${answers.suffix.replace(/^\./, "")}` : "";
    inputNum = answers.inputNum;
  }

  // if (!fpath) return console.log(chalk.yellow("请输入文件名"));

  const filePath = fpath || prefix;
  const fileCount = number || inputNum || 1;

  checkAndMkDir(filePath);

  if (fileCount && fileCount > 1) {
    for (let i = 0; i < fileCount; i++) {
      let tempPath = fpath;
      if (fpath) {
        const arr = fpath.split(".");
        tempPath =
          arr.length > 1
            ? `${arr.slice(0, arr.length - 1).join(".")}${i}.${
                arr[arr.length - 1]
              }`
            : `${fpath}${i}`;
      }

      genfile(tempPath || `${prefix}${i}${suffix}`);
    }
  } else {
    genfile(fpath ? fpath : `${prefix}${suffix}`);
  }

  console.log(chalk.green("创建完成"));
}

module.exports = file;
